<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/25
 * Time: 16:36
 */

namespace wechat\controllers;

use tt\common\components\TtPagination;
use tt\common\help\ModelHelper;
use tt\common\help\RequestHelp;
use tt\common\help\ResponseHelp;
use ttcommon\aop\annotation\ControllerAnnotation;
use ttcommon\base\Arrays;
use ttcommon\base\Data;
use ttext\backend\admin\hook\QuickMenuHook;

use wechat\models\WeVar;
use yii\base\UserException;

/**
 * @title [微信]模板变量
 */
class VarController extends BaseWechatController implements ControllerAnnotation
{
    /**
     * @title 列表
     * @return string
     */
    public function actionIndex()
    {
        if ($api = $this->hasApi()) {
            $query = WeVar::find();
            $pagination = new TtPagination(['totalCount' => $query->count()]);
            $data = [];
            foreach ($query->offset($pagination->offset)->limit($pagination->limit)->asArray()->each() as $item) {
                $data[] = $item;
            }
            $result = [
                'total' => $pagination->totalCount,
                'result' => $data
            ];
            ResponseHelp::send($result);
        }
        if (1 == Data::hasValue($_GET, 'btn')) {
            QuickMenuHook::$disabled = true;
            return $this->render('index_btn');
        }
        return $this->render('index');
    }

    private function findByName($name)
    {
        if (!$model = WeVar::findOne(['name' => $name])) {
            throw new \Exception('找不到指定的数据');
        }
        return $model;
    }

    /**
     * @title 添加/编辑
     */
    public function actionEdit($name = '')
    {
        QuickMenuHook::$disabled = true;
        $model = $name ? $this->findByName($name) : new WeVar();
        if (RequestHelp::isPost()) {
            $data = RequestHelp::requestData();

            $keys = ['name', 'value']; // 验证提交的数据
            Data::hasSet($data, $keys);
            // 如果要追加其它的键，请使用 array_merge($keys,[other])
            $model->attributes = Arrays::values($data, $keys);
            if ($model->validate() && $model->save()) {
                ResponseHelp::send($model->toArray());
            } else {
                throw new UserException(ModelHelper::errorMessages($model));
            }
        }
        return $this->render('edit', [
            'model' => $model
        ]);
    }

    /**
     * @title 删除
     */
    public function actionDelete($id)
    {
        if (RequestHelp::isPost()) {
            $model = $this->findByName($id);
            if ($model->delete() === false) {
                throw new UserException('删除失败');
            }
            ResponseHelp::send('删除成功');
        } else {
            RequestHelp::throwRequestMethodError();
        }
    }

    /**
     * @title 系统内置变量列表
     */
    public function actionSystem()
    {
        QuickMenuHook::$disabled = true;
        return $this->render('system');
    }
}